
package org.vasil.jouikov.services

class GoogleFeed {

    def static final dev_key = 'AIzaSyChLrfM7ZFo1X9MYdHbb9oAYrqCDTOHcQA'
    def static final max_result = 200

    def static token
    def static createTokenDay = new Date()

//println '>>> compare[==]:' << (today.minus(7).compareTo(createTokenDay) == 0)
//println '>>> compare[>]:' << (today.minus(7).compareTo(createTokenDay) > 0)
//println '>>> compare[<]:' << (today.minus(7).compareTo(createTokenDay) < 0)

    def getToken() {

        def today = new Date()
        if(!token || (today.minus(7).compareTo(createTokenDay) > 0)) { // check for old token one week(7days) ago
            createTokenDay = new Date()
            token = refreshToken()
        }
        return token
    }

//curl \
// --location https://www.google.com/accounts/ClientLogin \
// --data "Email=sandro%40compuvest.com&Passwd=3edc4rfv&service=structuredcontent&source=Test" \
// --header "Content-Type:application/x-www-form-urlencoded"
    def refreshToken() {

        def url = new URL("https://www.google.com/accounts/ClientLogin")

        def connection = url.openConnection()
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
        connection.setRequestMethod("POST")
        connection.doOutput = true

        def writer = new OutputStreamWriter(connection.outputStream)
        writer.write("Email=investintrust@gmail.com&Passwd=1okmnji989&service=structuredcontent&source=GoogleBase")
        writer.flush()
        writer.close()
        connection.connect()

        if(connection.responseCode == 200 || connection.responseCode == 201) {
            return connection.content.text.split(/Auth=/)[1].trim()
        }
        println "getToken() error occurred: ${connection.responseCode} : ${connection.responseMessage}"

        return 'Error'
    }

    def getCompuvestStock = { link, auth ->
//curl --header "Authorization:GoogleLogin \
//     Auth=DQAAAOIAAADAwwdxvrHur6hwQYyed7mJjkoegv8616tZsV1fTDk-pBWN5PEJTAqpvfjDj-Lxae45xETXwgSwOxaDAcuL4k0jyFjJEgfXuRvfvZ3RHKRO6VrFYEyFlfjMJl0Ucr9AGn4bsdBJK0Hltc1o8QC0hTml9El4q0AbAH6aCFJdzQwB0IznIG9fDNTtBvJpxjRpwT1s1vu1CjnrcTuUDIkzQmT2G2kBPe-P04aeGFlzERPrfJ15xJOPMw08zoUeYtLAwWc3M6VDxeGnCbeNZ0_6U4bYfZHBh-YX-dOwLdzxPWv9k0D3ujxczom4lZB8I2FazZM" --header "Content-Type:application/atom+xml" \
//     https://content.googleapis.com/content/v1/100115/items/products/generic&max-results=10

        if(!link) {
            link = "https://content.googleapis.com/content/v1/100115/items/products/generic?max-results=${max_result}" //&dry-run
        }

        try {
            def conn = link.toURL().openConnection()
            conn.setRequestProperty('Content-Type', "application/atom+xml");
            conn.setRequestProperty('Authorization', "GoogleLogin auth=${auth}");
            conn.setRequestMethod('GET')

            if(conn.responseCode == 200 || conn.responseCode == 201) {
                return ['status': 'Ok', 'body': conn.content.text]
            }
            return ['status': 'Err', 'body': "${conn.responseCode} : ${conn.responseMessage}"]
        }
        catch(error) {
            return ['status': 'Err', 'body': error]
        }
    }

    def getExparedAllStock = { link, auth ->
//curl --header "Authorization:GoogleLogin \
//     Auth=DQAAAOIAAADAwwdxvrHur6hwQYyed7mJjkoegv8616tZsV1fTDk-pBWN5PEJTAqpvfjDj-Lxae45xETXwgSwOxaDAcuL4k0jyFjJEgfXuRvfvZ3RHKRO6VrFYEyFlfjMJl0Ucr9AGn4bsdBJK0Hltc1o8QC0hTml9El4q0AbAH6aCFJdzQwB0IznIG9fDNTtBvJpxjRpwT1s1vu1CjnrcTuUDIkzQmT2G2kBPe-P04aeGFlzERPrfJ15xJOPMw08zoUeYtLAwWc3M6VDxeGnCbeNZ0_6U4bYfZHBh-YX-dOwLdzxPWv9k0D3ujxczom4lZB8I2FazZM" --header "Content-Type:application/atom+xml" \
//     https://content.googleapis.com/content/v1/100115/items/products/generic&max-results=10

        if(!link) {
            link = "https://content.googleapis.com/content/v1/100115/items/products/generic?max-results=${max_result}" // &dry-run
        }
        try {
            def conn = link.toURL().openConnection()
            conn.setRequestProperty('Content-Type', "application/atom+xml");
            conn.setRequestProperty('Authorization', "GoogleLogin auth=${auth}");
            conn.setRequestMethod('GET')

            if(conn.responseCode == 200 || conn.responseCode == 201) {
                return ['status': 'Ok', 'body': conn.content.text]
            }
            return ['status': 'Err', 'body': "${conn.responseCode} : ${conn.responseMessage}"]
        }
        catch(error) {
            return ['status': 'Err', 'body': error]
        }
    }

    def sendBatch = { xml, auth ->
/*
GET  /content/v1/SUB_ACCOUNT_ID/datafeeds/products/DATAFEED_ID HTTP/1.1
Host: content.googleapis.com
Content-Type: application/atom+xml
Authorization: GoogleLogin auth=AUTHORIZATION_TOKEN
*/
        try {
            def conn = "https://content.googleapis.com/content/v1/100115/items/products/generic/batch".toURL().openConnection()
            conn.setRequestProperty('Content-Type', "application/atom+xml");
            conn.setRequestProperty('Authorization', "GoogleLogin auth=${auth}");
            conn.setRequestMethod('POST')
            conn.doOutput = true

            conn.outputStream.withWriter { writer ->  writer << xml as String }

            if(conn.responseCode == 200 || conn.responseCode == 201) {
                return ['status': 'Ok', 'body': conn.content.text]
            }
            return ['status': 'Err', 'body': "${conn.responseCode} : ${conn.responseMessage}"]
        }
        catch(error) {
            return ['status': 'Err', 'body': error]
        }
    }

    def getPublicSearch = { query ->

        try {
                                                                                                                                      // ascending or descending
            def conn = "https://www.googleapis.com/shopping/search/v1/public/products?key=${dev_key}&country=US&alt=json&rankBy=price:ascending&maxResults=150&q=${query}".toURL().openConnection()

            if(conn.responseCode == 200 || conn.responseCode == 201) {
                return ['status': 'Ok', 'body': conn.content.text]
            }
            return ['status': 'Err', 'body': "${conn.responseCode} : ${conn.responseMessage}"]
        }
        catch(error) {
            return ['status': 'Err', 'body': error]
        }
    }

    def sendBatchReturn = {

        def xml = new StringBuilder()
//*
        // insert return status
        xml << "<?xml version='1.0' encoding='UTF-8'?>\n"
        xml << "<feed xmlns='http://www.w3.org/2005/Atom'>\n"
        xml << " <id>http://content.googleapis.com/content/account/100115/item/products/batch/1312399151867</id>\n"
        xml << " <updated>2011-08-03T19:19:12.041Z</updated>\n"
        xml << " <title>Batch Feed</title>\n"
        xml << " <entry xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:app='http://www.w3.org/2007/app' xmlns:sc='http://schemas.google.com/structuredcontent/2009'>\n"
        xml << "  <id>http://content.googleapis.com/content/account/100115/item/products/78979043636112</id>\n"
        xml << "  <published>2011-08-03T19:19:11.000Z</published>\n"
        xml << "  <updated>2011-08-03T19:19:11.906Z</updated>\n"
        xml << "  <app:edited>2011-08-03T19:19:11.906Z</app:edited>\n"
        xml << "  <title>Cisco 7600 Series IOS IP Transfer Point (ITP) S76ITPK912218IXD</title>\n"
        xml << "  <content>Cisco 7600 Series IOS IP Transfer Point (ITP) S76ITPK912218IXD</content>\n"
        xml << "  <link rel='self' type='application/atom+xml' href='https://content.googleapis.com/content/v1/100115/items/products/generic/online:en:US:716013025-00'/>\n"
        xml << "  <link rel='edit' type='application/atom+xml' href='https://content.googleapis.com/content/v1/100115/items/products/generic/online:en:US:716013025-00'/>\n"
        xml << "  <link rel='alternate' type='text/html' href='http://www.compuvest.com/Search.jsp?Search=S76ITPK912218IXD&amp;advsite=froogle&amp;sku=716013025-00&amp;dp=0:CMS:10080600:0:0:'/>\n"
        xml << "  <sc:adult>false</sc:adult>\n"
        xml << "  <sc:attribute name='shipping weight' type='float' unit='lb'>1.0</sc:attribute>\n"
        xml << "  <sc:attribute name='condition' type='text'>new</sc:attribute>\n"
        xml << "  <sc:attribute name='mpn' type='text'>S76ITPK912218IXD</sc:attribute>\n"
        xml << "  <sc:attribute name='price' type='float' unit='USD'>100806.0</sc:attribute>\n"
        xml << "  <sc:attribute name='quantity' type='int'>1</sc:attribute>\n"
        xml << "  <sc:attribute name='gtin' type='text'>0</sc:attribute>\n"
        xml << "  <sc:attribute name='brand' type='text'>Cisco</sc:attribute>\n"
        xml << "  <sc:attribute name='google product category' type='text'>Networking &gt; CISCO Network Devices</sc:attribute>\n"
        xml << "  <sc:attribute name='product type' type='text'>Networking &gt; CISCO Network Devices</sc:attribute>\n"
        xml << "  <sc:attribute name='availability' type='text'>in stock</sc:attribute>\n"
        xml << "  <sc:attribute name='manufacturer' type='text'>Cisco</sc:attribute>\n"
        xml << "  <batch:operation type='insert'/>\n"
        xml << "  <batch:status code='201' reason='Created'/>\n"
        xml << "  <sc:content_language>en</sc:content_language>\n"
        xml << "  <sc:expiration_date>2011-09-02T12:19:11.000-07:00</sc:expiration_date>\n"
        xml << "  <sc:id>716013025-00</sc:id>\n"
        xml << "  <sc:image_link>http://img.compuvest.com/0/716013025-00.jpg</sc:image_link>\n"
        xml << "  <sc:target_country>US</sc:target_country>\n"
        xml << " </entry>\n"
        xml << " <entry xmlns:batch='http://schemas.google.com/gdata/batch'>\n"
        xml << "  <id>http://content.googleapis.com/content/account/100115/item/products/716013025-00</id>\n"
        xml << "  <updated>2011-08-03T18:19:45.042Z</updated>\n"
        xml << "  <title>Deleted</title>\n"
        xml << "  <content>Deleted</content>\n"
        xml << "  <batch:operation type='delete'/>\n"
        xml << "  <batch:status code='200' reason='Success'/>\n"
        xml << " </entry>\n"
        xml << " <entry xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005'>\n"
        xml << "  <id>http://content.googleapis.com/content/account/100115/item/products/716013025-00</id>\n"
        xml << "  <updated>2011-08-03T20:38:50.294Z</updated>\n"
        xml << "  <title>Error</title>\n"
        xml << "  <content type='application/vnd.google.gdata.error+xml'>\n"
        xml << "   <gd:errors>\n"
        xml << "    <gd:error>\n"
        xml << "     <gd:domain>sc</gd:domain>\n"
        xml << "     <gd:code>validation/missing_required</gd:code>\n"
        xml << "     <gd:location type='other'>title</gd:location>\n"
        xml << "     <gd:internalReason>Title is required.</gd:internalReason>\n"
        xml << "    </gd:error>\n"
        xml << "   </gd:errors>\n"
        xml << "  </content>\n"
        xml << "  <batch:operation type='update'/>\n"
        xml << "  <batch:status code='400' reason='Title is required.'/>\n"
        xml << " </entry>\n"
        xml << " <entry xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005'>\n"
        xml << "  <updated>2011-08-03T18:43:02.668Z</updated>\n"
        xml << "  <title>Error</title>\n"
        xml << "  <content type='application/vnd.google.gdata.error+xml'></content>\n"
        xml << "  <batch:operation type='insert'/>\n"
        xml << "  <batch:status code='400' reason='The item is missing a required attribute.'/>\n"
        xml << " </entry>\n"
        xml << " <entry xmlns:batch='http://schemas.google.com/gdata/batch'>\n"
        xml << "  <id>http://content.googleapis.com/content/account/100115/item/products/batch/1312394440979/fatal</id>\n"
        xml << "  <updated>2011-08-03T18:00:41.079Z</updated>\n"
        xml << "  <title>Fatal Error</title>\n"
        xml << "  <content>Feed processing was interrupted.</content>\n"
        xml << "  <batch:interrupted error='0' parsed='0' reason='The element type &quot;batch:operation&quot; must be terminated by the matching end-tag &quot;&lt;/batch:operation&gt;&quot;.' success='0' unprocessed='0'/>\n"
        xml << " </entry>\n"
        xml << "<entry xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005'>\n"
        xml << " <id>716013025-00</id>\n"
        xml << " <updated>2011-08-03T18:03:55.795Z</updated>\n"
        xml << " <title>Error</title>\n"
        xml << " <content type='application/vnd.google.gdata.error+xml'>\n"
        xml << " </content>\n"
        xml << " <batch:operation type='delete'/>\n"
        xml << " <batch:status code='400' reason='Invalid entry Id/Uri'/>\n"
        xml << "</entry>\n"
        xml << "</feed>"

        return xml
    }
}

